<?php

namespace App\Trip\Traits;

use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use function response;

trait Response
{
    private array $headers   = [];
    private int   $http_code = 200;

    function success(string $msg = 'success', array|Collection|JsonResource|null $data = [], ?int $http_code = 200)
    {
        $res = [
            'code'    => 0,
            'message' => __($msg),
            'data'    => $data,
        ];
        $this->setHttpCode($http_code);
        return $this->response($res);
    }

    public function setHttpCode(int $http_code)
    {
        $this->http_code = $http_code;
    }

    private function response(array $response_data)
    {
        $headers       = [];
        $this->headers = array_merge($this->headers, $headers);
        if (empty($this->headers)) {
            response($response_data, $this->http_code);
        }
        return response($response_data, $this->http_code, $this->headers);
    }

    public function setHeaders(array $headers)
    {
        $this->headers = $headers;
    }

    /**
     * @param int                                $code
     * @param string                             $msg
     * @param array|Collection|JsonResource|null $data
     * @param int|null                           $http_code
     *
     * @return Application|ResponseFactory|\Illuminate\Http\Response
     */
    function error(int $code = 1, string $msg = 'failed', array|Collection|JsonResource|null $data = [], ?int $http_code = 200)
    {
        $res = [
            'code'    => $code,
            'message' => __($msg),
            'data'    => $data,
        ];
        try {
            Log::error(json_encode([
                'url'     => request()->url(),
                'request' => request()->all(),
                'msg'     => $msg,
                'code'    => $code,
                'data'    => $data,
            ],
                JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        } catch (Exception $e) {

        }
        $this->setHttpCode($http_code);
        return $this->response($res);
    }

}